import { addDataset } from "@/external-api";
import styles from "@/styles/DataManage.module.css";
import { PlusSquareOutlined } from "@ant-design/icons";
import { Button, Select, message, Modal, Form, Input } from "antd";
import { useRouter } from "next/router";
import { useState } from "react";

type FieldType = {
  name?: string;
  path?: string;
};

const ToolBar = ({ change, setKey }: any) => {
  const [open, setOpen] = useState(false);
  const [messageApi, messageHolder] = message.useMessage();
  const [form] = Form.useForm();
  const router = useRouter();

  const handleChange = (value: string) => {
    change(value);
  };

  const showModal = () => {
    setOpen(true);
  };

  const closeModal = () => {
    form.resetFields();
    setOpen(false);
  };

  const onFinish = async (values: any) => {
    const res = await addDataset(values);
    if (res.code === 0) {
      closeModal();
      setKey((prev: number) => prev + 1);
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <div className={styles.toolBar}>
      <span>样本集类型</span>
      <Select
        defaultValue="all"
        style={{ width: 180 }}
        onChange={handleChange}
        options={[
          { value: "all", label: "所有" },
          { value: "original", label: "原始样本" },
          { value: "expanded", label: "增广样本" },
        ]}
      />
      <Button type="primary" onClick={showModal}>
        <PlusSquareOutlined />
        导入
      </Button>
      {messageHolder}
      <Modal title="样本集导入" open={open} onCancel={closeModal} footer={null}>
        <Form
          form={form}
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600, marginTop: 20 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item<FieldType>
            label="名称"
            name="name"
            rules={[{ required: true, message: "请输入样本集名称" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item<FieldType>
            label="本地路径"
            name="path"
            rules={[{ required: true, message: "请输入样本集本地路径" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 7, span: 16 }}>
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginRight: 12 }}
            >
              确定
            </Button>
            <Button type="default" htmlType="reset">
              重置
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ToolBar;
